<template>
  <div class="flow">
    <div class="formLook">
      <TitleComponent title="合同登记" />
      <div class="contract-container">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          label-position="top"
        >
          <!-- 合同信息 -->
          <div class="section">
            <div class="section-title">
              <span>合同信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item
                  label="员工账号："
                  prop="employeeInfoId"
                  class="compact-form-item"
                >
                  <div class="account-input-wrapper">
                    <el-input
                      v-model="form.userName"
                      placeholder="自动带出"
                      disabled
                      class="compact-input"
                    >
                      <template #suffix>
                        <el-tooltip content="选择员工账号" placement="top">
                          <el-button
                            type="primary"
                            link
                            @click="InfoClick"
                            class="account-select-btn"
                          >
                            <el-icon><User /></el-icon>
                          </el-button>
                        </el-tooltip>
                      </template>
                    </el-input>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工号：" prop="jobNumber">
                  <el-input
                    disabled
                    v-model="form.jobNumber"
                    placeholder="自动带出"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="合同名称：" prop="contractName">
                  <el-input
                    v-model="form.contractName"
                    placeholder="请输入合同名称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同编号：" prop="contractNo">
                  <el-input
                    v-model="form.contractNo"
                    placeholder="请输入合同编号"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="签订类型：" prop="signType">
                  <el-radio-group v-model="form.signType">
                    <el-radio
                      v-for="(option, index) in sysConcludeType"
                      :key="option.value"
                      :label="option.value"
                    >
                      {{ option.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同类型：" prop="contractType">
                  <el-select v-model="form.contractType" placeholder="请选择">
                    <el-option
                      v-for="item in sys_contract_type"
                      :key="item.value"
                      :label="item.label"
                      :value="Number(item.value)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <!-- 待定 -->
                <el-form-item label="合同期限（年）：" prop="yearNum">
                  <template #label>
                    <span class="label-container">
                      <span>
                        合同期限（年）：
                        <!-- <IconInfoTip
                          size="20"
                          color="#E81212"
                          @click.native="showHint = !showHint"
                          class="icon-tip"
                        /> -->

                        <el-icon
                          @click.native="showHint = !showHint"
                          color="#ff4d4f"
                          :size="16"
                          ><WarningFilled
                        /></el-icon>
                        <!-- 提示信息容器 -->
                        <transition name="fade">
                          <div
                            v-show="showHint"
                            class="legal-notice-container"
                            @click.stop
                          >
                            <div class="legal-notice-content">
                              <p>
                                {{ contractPeriod }}
                              </p>
                            </div>
                          </div>
                        </transition>
                      </span>
                    </span>
                  </template>
                  <el-input
                    v-model="form.yearNum"
                    placeholder="合同期限"
                    @input="validateContractTerm"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同签订日期：" prop="contractSignTime">
                  <el-date-picker
                    style="width: 100%"
                    v-model="form.contractSignTime"
                    type="date"
                    placeholder="请选择合同签订日期"
                    @change="handleDateChange"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 系统自动判断，如果该员工是兼职员工，在合同登记页面：是否有试用期只读默认为：否，试用期期限（月），试用期到期日期字段不显示。并给予提示语：“兼职人员不能约定试用期”； -->
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item
                  label="是否有试用期："
                  prop="isHaveProbationPeriod"
                >
                  <template #label>
                    <span>
                      <span style="display: flex"
                        >是否有试用期：
                        <!-- <IconInfoTip size="20" color="#ff4d4f" /> -->

                        <el-icon color="#ff4d4f" :size="16"
                          ><WarningFilled
                        /></el-icon>

                        <div class="risk-notice-container">
                          <div class="risk-notice-content">
                            <p>{{ probation }}</p>
                          </div>
                        </div>
                      </span>
                    </span>
                  </template>
                  <el-radio-group v-model="form.isHaveProbationPeriod">
                    <el-radio
                      v-for="(option, index) in sysWhetherType"
                      :key="index"
                      :label="option.value"
                    >
                      {{ option.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  prop="probationPeriod"
                  :error="probationPeriodError"
                  v-if="form.isHaveProbationPeriod == 0"
                >
                  <template #label>
                    <span>
                      <span>试用期期限（月）：</span>
                    </span>

                    <div class="form-tip">
                      试用期期限不满一个月，请手动选择到期日期
                    </div>
                  </template>

                  <el-input
                    v-model="form.probationPeriod"
                    @input="validateProbationTerm"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                  <!-- 风险提示 -->
                  <transition name="el-zoom-in-top">
                    <div v-if="showRiskHint" class="compliance-alert">
                      <el-icon color="#ff4d4f" :size="16"
                        ><WarningFilled
                      /></el-icon>

                      <div class="risk-notice-container">
                        <div class="risk-notice-content">
                          <p>{{ riskMessage }}</p>
                        </div>
                      </div>
                    </div>
                  </transition>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="试用期到期日期："
                  prop="probationArriveTime"
                  v-if="
                    form.isHaveProbationPeriod == 0 && form.contractSignTime
                  "
                >
                  <template #label>
                    <span>
                      <span>试用期到期日期：</span>
                    </span>
                    <div class="form-tip">
                      依据试用期期限自动计算，可手动修改
                    </div>
                  </template>
                  <el-date-picker
                    style="width: 100%"
                    v-model="form.probationArriveTime"
                    type="date"
                    placeholder="请选择"
                  ></el-date-picker>

                  <!-- 风险提示容器 -->

                  <div v-show="showRiskWarning" class="risk-warning">
                    <span style="display: flex">
                      <el-icon color="#ff4d4f" :size="16"
                        ><WarningFilled
                      /></el-icon>

                      <div class="risk-notice-container">
                        <div class="risk-notice-content">
                          <p>
                            {{ hasExpired }}
                          </p>
                        </div>
                      </div>
                    </span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="转正设置：" prop="regularization">
                  <el-radio-group v-model="form.regularization">
                    <el-radio
                      v-for="(option, index) in sys_regularization_type"
                      :key="index"
                      :label="option.value"
                    >
                      {{ option.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row> -->
          </div>

          <div class="section-title">
            <span>双方信息</span>
          </div>
          <!-- 甲方信息 -->
          <div class="section">
            <div class="section-title">
              <span>甲方信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="公司主体：" prop="companyBody">
                  <el-select v-model="form.companyBody" placeholder="请选择">
                    <el-option label="南京公司" :value="0"></el-option>
                    <el-option label="郑州公司" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="法定代表人：" prop="legalRepresentativeId">
                  <el-select
                    v-model="form.legalRepresentativeId"
                    placeholder="请选择"
                  >
                    <el-option label="法定代表人A" :value="0"></el-option>
                    <el-option label="法定代表人B" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="公司地址：" prop="companyAddress">
                  <el-input
                    v-model="form.companyAddress"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 乙方信息 -->
          <div class="section">
            <div class="section-title">
              <span>乙方信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="姓名：" prop="name">
                  <span>{{ form.name }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="性别：" prop="sex">
                  <span>{{
                    form.sex === 0 ? "男" : form.sex === 1 ? "女" : ""
                  }}</span>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="年龄：" prop="age">
                  <span>{{ form.age }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="国籍：" prop="">
                  <span>{{}}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="岗位名称：" prop="applicationPositonName">
                  <span>{{ form.applicationPositonName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门：" prop="deptName">
                  <span>{{ form.deptName }}</span>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="岗位性质：" prop="JobNature">
                  <span>{{ form.JobNature }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职级：" prop="PositionLevel">
                  <span>{{ positionLevelLabel }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="直属领导：" prop="directLeaderName">
                  <span>{{ form.directLeaderName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="最高领导：" prop="supremeLeaderName">
                  <span>{{ form.supremeLeaderName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="家庭住址：" prop="homeAddress">
                  <span>{{ form.homeAddress }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 其他信息 -->
            <div class="section">
              <div class="section-title">
                <span>其他信息</span>
              </div>
              <el-table :data="form.contractInfoEntities" style="width: 100%">
                <el-table-column
                  type="index"
                  label="序号"
                  width="80"
                ></el-table-column>
                <el-table-column
                  prop="startTime"
                  label="合同签订日期"
                ></el-table-column>
                <el-table-column
                  prop="endTime"
                  label="合同到期日期"
                ></el-table-column>
                <el-table-column
                  prop="yearNum"
                  label="合同期限"
                ></el-table-column>
                <el-table-column
                  prop="signingTimes"
                  label="签订次数"
                ></el-table-column>
                <el-table-column
                  prop="contractNo"
                  label="合同编号"
                ></el-table-column>
              </el-table>
            </div>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注：" prop="laborRelationsRemark">
                  <el-input
                    v-model="form.laborRelationsRemark"
                    type="textarea"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="创建人：" prop="createName">
                  <el-input disabled v-model="form.createName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建时间：" prop="createTime">
                  <el-input disabled v-model="form.createTime"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="是否签署竞业限制协议："
                  prop="isSignCompetitionAgreement"
                >
                  <el-radio-group v-model="form.isSignCompetitionAgreement">
                    <el-radio
                      v-for="(option, index) in sysWhetherType"
                      :key="index"
                      :label="option.value"
                    >
                      {{ option.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="section">
            <div class="section-title">
              <span>附件</span>
            </div>
            <!-- <el-form-item label="劳动合同：" prop="contractFile">
              <Upload
                :modelValue="form.contractFile"
                :isShowTip="false"
                @update:modelValue="uploadContractFile"
                @delete="contractFileDelete"
              ></Upload>
            </el-form-item> -->
            <el-form-item label="劳动合同：" prop="contractFile">
              <div class="contract-upload-container">
                <div class="legal-notice">
                  <span class="label-text">劳动合同：</span>
                  <span class="warning-text"
                    >（用人单位必须自用工之日起，一个月内与劳动者订立书面劳动合同）</span
                  >
                </div>
                <Upload
                  :modelValue="form.contractFile"
                  :isShowTip="false"
                  @update:modelValue="uploadContractFile"
                  @delete="contractFileDelete"
                ></Upload>
              </div>
            </el-form-item>
            <el-form-item label="劳动合同签收确认：" prop="contractSignConfirm">
              <Upload
                :modelValue="form.contractSignConfirm"
                :isShowTip="false"
                @update:modelValue="uploadContractSignConfirm"
                @delete="ContractSignConfirmDelete"
              ></Upload>
            </el-form-item>
            <el-form-item
              label="竞业限制协议附件："
              prop="competitionAgreementFile"
            >
              <Upload
                :modelValue="form.competitionAgreementFile"
                :isShowTip="false"
                @update:modelValue="uploadCompetitionAgreementFile"
                @delete="CompetitionAgreementFileDelete"
              ></Upload>
            </el-form-item>
          </div>
          <div class="button-group">
            <el-button @click="resetForm">取消</el-button>
            <el-button @click="saveForm">保存</el-button>
            <el-button type="primary" @click="submitForm">提交</el-button>
          </div>
        </el-form>
      </div>
      <EmployeeDialog
        ref="employeeDialogRef"
        @update:selected="handleEmployeeSelected"
      />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import IconInfoTip from "@/components/svgImg/index.vue";
import EmployeeDialog from "@/components/EmployeeDialog/index.vue";
import TitleComponent from "@/components/TitleComponent.vue";
import { useRouter } from "vue-router";
import Upload from "@/components/FileUpload/index.vue";
import { transferInfoId } from "@/api/employeeRelations/transferManagement.js";

import { Warning } from "@element-plus/icons-vue";
import { formatDate } from "@/utils/index.js";
import {
  saveLaborRelation,
  saveLaborRelationDetails,
} from "@/api/laborrelations/index.js";
import useUserStore from "@/store/modules/user";
import { fetchKeyData } from "@/utils/api";

const userStore = useUserStore();
const formRef = ref(null);
const { proxy } = getCurrentInstance();
const {
  sys_conclude_type,
  sys_whether_type,
  sys_regularization_type,
  sys_contract_type,
} = proxy.useDict(
  "sys_conclude_type",
  "sys_whether_type",
  "sys_regularization_type",
  "sys_contract_type"
);

const levelMap = {
  0: "初级",
  1: "中级",
  2: "高级",
};

const showRiskWarning = ref(false);
const riskMessage = ref(null);
const legalProbation = {
  0.25: 0, // 3个月
  1: 1, // 1年
  2: 2, // 2年
  3: 6, // 3年+
};

const positionLevelLabel = computed(() => levelMap[form.positionLevel] || "");
const showHint = ref(false);

const showRiskHint = ref(false);
const probationPeriodError = ref("");

const sysConcludeType = computed(() => {
  return sys_conclude_type.value.map((item) => ({
    label: item.label,
    value: Number(item.value), // 确保为数字类型
  }));
});
// sys_whether_type 是否是试用期
const sysWhetherType = computed(() => {
  return sys_whether_type.value.map((item) => ({
    label: item.label,
    value: Number(item.value), // 确保为数字类型
  }));
});

const employeeDialogRef = ref(null);
const router = useRouter();
const route = useRoute();
const probation = ref(""); //劳动试用期提示语
const contractPeriod = ref(""); //合同期限提示语

const hasExpired = ref(""); //试用期到期
// sys_conclude_type
const form = reactive({
  employeeInfoId: "",
  employeeName: "",
  // 乙方
  jobNumber: "", //工号
  name: "", //姓名
  sex: "", //性别
  age: "", //年龄
  applicationPositonName: "", //岗位名称
  deptName: "", //部门
  directLeaderName: "", //直属领导
  supremeLeaderName: "", //最高领导
  contractName: "", //合同名称
  contractNo: "", //合同编号
  signType: "",
  contractType: "",
  yearNum: "", //合同期限
  contractSignTime: "",
  isHaveProbationPeriod: "1",
  probationPeriod: "",
  probationArriveTime: "",
  companyBody: "",
  legalRepresentativeId: "",
  companyAddress: "",
  employeeWorkNumber: "",
  positionName: "",
  JobNature: "",
  PositionLevel: "",
  homeAddress: "",
  laborRelationsRemark: "",
  isSignCompetitionAgreement: "",
  contractFile: [],
  contractSignConfirm: [],
  competitionAgreementFile: [],
  createName: "",
  createTime: "",
  contractInfoEntities: [],
});

const formInfo = reactive({
  employeeInfoId: "", //员工主键id
  signType: "", // 签订类型
  contractName: "", //合同名称
  contractNo: "", //合同编号
  contractType: "", // 合同类型
  yearNum: "", //合同期限
  probationPeriod: "", // 试用期期限(月)
  contractSignTime: "", //合同签订日期
  isHaveProbationPeriod: "", //是否有试用期
  probationArriveTime: "", //试用期到期日期
  companyBody: "", //公司主体
  legalRepresentativeId: "", //法定代表人
  companyAddress: "", //公司地址
  homeAddress: "",
  laborRelationsRemark: "", //备注
  isSignCompetitionAgreement: "", //是否签署竞业限制协议(0 已签署 1 未签署)
  contractFile: [],
  contractSignConfirm: [],
  competitionAgreementFile: [],
  createName: "",
  createTime: "",
  contractInfoEntities: [],
});

const rules = reactive({
  employeeInfoId: [
    { required: true, message: "请选择员工账号", trigger: "change" },
  ],
  workNumber: [{ required: true, message: "请输入工号", trigger: "blur" }],
  signType: [{ required: true, message: "请选择签订类型", trigger: "change" }],
  contractType: [
    { required: true, message: "请选择合同类型", trigger: "change" },
  ],
  yearNum: [{ required: true, message: "请选择合同类型", trigger: "change" }],
  contractSignTime: [
    { required: true, message: "请选择合同签订日期", trigger: "change" },
  ],

  probationPeriod: [
    { required: true, message: "请输入试用期期限", trigger: "blur" },
  ],
  probationArriveTime: [
    { required: true, message: "请选择试用期到期日期", trigger: "change" },
  ],
  regularization: [
    { required: true, message: "请选择转正设置", trigger: "change" },
  ],
  companyBody: [
    { required: true, message: "请选择公司主体", trigger: "change" },
  ],
  legalRepresentativeId: [
    { required: true, message: "请输入法定代表人", trigger: "blur" },
  ],
  companyAddress: [
    { required: true, message: "请输入公司地址", trigger: "blur" },
  ],
  employeeName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  employeeWorkNumber: [
    { required: true, message: "请输入工号", trigger: "blur" },
  ],
  positionName: [
    { required: true, message: "请输入岗位名称", trigger: "blur" },
  ],
});
// 监听日期变化
const handleDateChange = (value) => {
  if (!value) {
    // 如果日期被清空
    form.contractSignTime = "";

    // 可以在这里触发一个事件或执行其他逻辑
    console.log("合同签订日期已被清空");
  } else {
    // 如果日期被设置
    console.log("合同签订日期已设置为:", value);
  }
};

const validateContractTerm = (value) => {
  // 使用正则表达式过滤掉非数字字符
  form.yearNum = Number(value.replace(/[^0-9]/g, ""));
  validateTermRelation();
  validateCompliance();
};
const validateProbationTerm = (value) => {
  form.probationPeriod = value.replace(/[^0-9]/g, "");

  validateTermRelation();
  validateCompliance();
};

// 获取法定最长试用期
const getLegalMaxProbation = (year) => {
  if (year >= 3) return 6;
  if (year >= 1) return 2;
  if (year >= 0.25) return 1;
  return 0;
};

const validateTermRelation = () => {
  const contractYear = form.yearNum || 0;
  const probationMonth = form.probationPeriod || 0;

  // 转换为月份比较
  const contractMonth = contractYear * 12;

  // 风险情况1：试用期等于合同期
  if (probationMonth >= contractMonth) {
    showRiskWarning.value = true;
    return;
  }

  // 风险情况2：试用期达到法定上限
  const legalMax = getLegalMaxProbation(contractYear);
  if (probationMonth >= legalMax) {
    showRiskWarning.value = true;

    return;
  }

  showRiskWarning.value = false;
};

// 主验证方法
const validateCompliance = () => {
  const contractYears = parseFloat(form.yearNum) || 0;
  const probationMonths = parseFloat(form.probationPeriod) || 0;
  const contractMonths = contractYears * 12;

  showRiskHint.value = false;
  probationPeriodError.value = "";

  // 输入有效性检查
  if (contractMonths < 3 && contractMonths > 0) {
    probationPeriodError.value = "合同期限需≥3个月";
    return;
  }

  // 获取法定最大试用期
  let legalMax = 0;
  if (contractMonths >= 36) {
    // ≥3年
    legalMax = 6;
  } else if (contractMonths >= 12) {
    // 1-3年
    legalMax = 2;
  } else if (contractMonths >= 3) {
    // 3个月-1年
    legalMax = 1;
  }

  // 风险判断
  if (probationMonths > legalMax) {
    showRiskHint.value = true;
    probationPeriodError.value = "试用期超过法定限制";
    generateRiskMessage(contractYears, legalMax);
  } else if (probationMonths === 0 && legalMax > 0) {
    probationPeriodError.value = "请填写试用期期限";
  }
};

// 生成动态提示信息
const generateRiskMessage = (years, legalMax) => {
  const ranges = {
    0.25: { min: 3, max: 12, text: "3个月≤合同期限<1年" },
    1: { min: 12, max: 36, text: "1年≤合同期限<3年" },
    3: { min: 36, max: Infinity, text: "合同期限≥3年" },
  };

  const rangeKey = years >= 3 ? 3 : years >= 1 ? 1 : 0.25;
  const currentRange = ranges[rangeKey];

  // riskMessage.value = `试用期约定必须与劳动合同期限严格匹配！当前${
  //   currentRange.text
  // }，法定试用期不得超过${legalMax}个月。建议：
  //   ${
  //     legalMax === 6
  //       ? "- 长期合同（≥3年）充分利用6个月试用期考核"
  //       : "- 短期合同（＜1年）慎用试用期"
  //   }
  //   - 所有试用期约定需书面明确考核标准。`;
};

// form.yearNum
const calculateProbationArriveTime = () => {
  if (form.contractSignTime && form.probationPeriod) {
    const startDate = new Date(form.contractSignTime);
    const probationPeriod = parseInt(form.probationPeriod, 10);

    if (isNaN(probationPeriod)) {
      ElMessage.error("请输入有效的试用期期限");
      return;
    }

    startDate.setMonth(startDate.getMonth() + probationPeriod);
    form.probationArriveTime = startDate;
  } else {
    form.probationArriveTime = null;
  }
};
watch(() => form.probationPeriod, calculateProbationArriveTime);
watch(() => form.contractSignTime, calculateProbationArriveTime);
// 无固定期限劳动合同
// watch(
//   () => form.isIndefinite,
//   (newVal) => {
//     if (newVal) validateCompliance();
//   }
// );
const getCurrentDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

onMounted(async () => {
  form.createTime = getCurrentDate();
  // getAcquire();
  if (route.query.id) {
    getlaborreDetails(route.query.id);
  } else {
    // 如果是编辑那么便不执行
    form.createName = userStore.user.nickName;
  }

  try {
    const [perIod, contract, Notice, Expired] = await Promise.all([
      fetchKeyData("riskKey", "劳动key7"),
      fetchKeyData("riskKey", "劳动key5"),
      fetchKeyData("riskKey", "劳动key3"),
      fetchKeyData("riskKey", "劳动key4"),
    ]);

    probation.value = perIod?.data?.[0]?.value || "";
    contractPeriod.value = contract?.data?.[0]?.value || "";

    riskMessage.value = Notice?.data?.[0]?.value || "";
    hasExpired.value = Expired?.data?.[0]?.value || "";
  } catch (error) {
    console.error("数据获取失败:", error);
  }
});

const getlaborreDetails = async (id) => {
  const res = await saveLaborRelationDetails(id);
  if (res.data) {
    Object.keys(res.data).forEach((item) => {
      if (res.data[item]) {
        form[item] = res.data[item];
        form.signType = Number(res.data.signType);
        form.isHaveProbationPeriod = Number(res.data.isHaveProbationPeriod);
        form.companyBody = Number(res.data.companyBody);
        form.legalRepresentativeId = Number(res.data.legalRepresentativeId);
        form.isSignCompetitionAgreement = Number(
          res.data.isSignCompetitionAgreement
        );

        form.contractInfoEntities = res.data.contractInfoEntities;
      }
    });
  }
};

// 根据选中的员工id查询
function handleEmployeeSelected(item) {
  console.log(item, "选中的值");
  console.log(item[0]);
  // selectedItem.value = item; // 更新选中的项
  let params = {
    id: item[0],
  };
  transferInfoId(params).then((res) => {
    console.log(res.data, "调岗信息");
    if (res.data) {
      Object.keys(res.data).forEach((item) => {
        // 先重置为默认值（根据类型处理）
        form[item] = typeof res.data[item] === "number" ? 0 : "";
        // // 赋值前进行空值保护
        form[item] = res.data[item] ?? form[item];
        form.employeeInfoId = res.data.id;
      });
    }
  });
}

const InfoClick = async () => {
  employeeDialogRef.value.open((value) => {});
};
const handleFormSubmit = (isSubmit) => {
  console.log(form, "form");
  Object.keys(form).forEach((item) => {
    if (formInfo[item] == "") {
      console.log(form.contractSignTime, "form.contractSignTime");
      formInfo[item] = form[item];
      formInfo.saveOrSubmit = isSubmit ? 0 : 1; // 保存和提交
      formInfo.startTime = form.contractSignTime; /** 合同签订时间 */
      (formInfo.emId = formInfo.employeeInfoId) /** 员工id */,
        (formInfo.contractSignTime = formatDate(
          formInfo.contractSignTime
        ).dates);
      formInfo.probationArriveTime = formatDate(
        formInfo.probationArriveTime
      ).dates;
      if (route.query.id) {
        formInfo.laborId = Number(route.query.id);
      }
    }
  });

  formRef.value.validate((valid) => {
    if (valid) {
      saveLaborRelation(formInfo)
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success(isSubmit ? "提交成功" : "保存成功");
            // 进行相应的页面跳转或其他操作

            resetForm();
          } else {
            ElMessage.error(res.message || "操作失败");
          }
        })
        .catch((error) => {
          console.error("Error during transfer:", error);
        });
    } else {
      ElMessage.error("请填写必填项");
    }
  });
};

const saveForm = () => {
  handleFormSubmit(false); // 保存操作
};

const submitForm = () => {
  handleFormSubmit(true); // 提交操作
};

const handlePreview = (file) => {
  console.log("Preview:", file);
};

const handleRemove = (file, fileList) => {
  console.log("Remove:", file, fileList);
};

const beforeRemove = (file, fileList) => {};
const uploadFiles = (files) => {
  if (!form.attachments) {
    form.attachments = [];
  }
  form.attachments.push({
    file: files,
  });
};
// 劳动合同
const uploadContractFile = (files) => {
  if (!form.contractFile) {
    form.contractFile = [];
  }
  form.contractFile.push({
    file: files,
  });
};
// 劳动合同删除
const contractFileDelete = (updatedFiles) => {
  console.log(updatedFiles, "updatedFiles");
  form.contractFile = updatedFiles;
};

// uploadContractSignConfirm
// 劳动合同
const uploadContractSignConfirm = (files) => {
  if (!form.contractSignConfirm) {
    form.contractSignConfirm = [];
  }
  form.contractSignConfirm.push({
    file: files,
  });
};
// 劳动合同删除
const ContractSignConfirmDelete = (updatedFiles) => {
  console.log(updatedFiles, "updatedFiles");
  form.contractSignConfirm = updatedFiles;
};

// uploadContractSignConfirm
// 劳动合同
const uploadCompetitionAgreementFile = (files) => {
  if (!form.competitionAgreementFile) {
    form.competitionAgreementFile = [];
  }
  form.competitionAgreementFile.push({
    file: files,
  });
};
// 劳动合同删除
const CompetitionAgreementFileDelete = (updatedFiles) => {
  console.log(updatedFiles, "updatedFiles");
  form.competitionAgreementFile = updatedFiles;
};
const resetForm = () => {
  router.go(-1);
};
</script>

<style scoped lang="scss">
.contract-container {
  margin: 0 auto;
  padding: 0px 0px 0px 10px;
  background-color: #fff;
  border-radius: 8px;
}

.section {
  margin: 0 0 30px 20px; /* 合并 margin 属性 */
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-row {
  margin-bottom: 20px;
}

.button-group {
  margin-top: 20px;
  text-align: center;
}
.section-title {
  font-size: 16px;
  height: 17px;
  line-height: 15px;
  font-weight: bold;
  padding-left: 10px;
  border-left: 3px solid #409eff;
  margin: 15px 0px;

  margin-bottom: 20px;
  color: #303133;
}
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.hint-notice-container {
  border-radius: 4px;
  border: 1px solid #007bff;
  background: #e5f2ff;
  margin-left: 10px;
}

.hint-notice-content p {
  margin: 0;
  color: #007bff;
  padding: 5px;
  font-weight: bold;
  font-size: 10px;
  line-height: 1.6;
  text-align: justify;
}

/* 图标容器需要相对定位 */
.label-container {
  position: relative;
}

.legal-notice-container {
  position: absolute;
  left: 100%; /* 调整到图标右侧 */
  top: 50%;
  transform: translateY(-50%);
  z-index: 9999;
  min-width: 300px;
  // background: #fff;
  // border: 1px solid #ebeef5;

  // border: 1px solid #ffae00;
  // background: #fff7e5;
  // margin-left: 10px;

  // border-radius: 4px;
  // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  // padding: 12px;
  border-radius: 4px;
  border: 1px solid var(--Primary7-500, #e81212);
  background: var(--Primary7-50, #fde7e7);
  box-shadow: 0px 8px 12px 0px rgba(47, 4, 4, 0.1);
}

.legal-notice-content p {
  padding: 5px;
  color: var(--Primary7-500, #e81212);
  text-align: justify;
  font-family: "Source Han Sans CN";
  font-size: 12px;
  font-style: normal;
  font-weight: 500;
  line-height: normal;
}

.hint-notice-content {
  font-size: 12px;
  line-height: 1.5;
  color: #606266;
}

.icon-tip {
  cursor: pointer;
  vertical-align: middle;
  margin-left: 4px;
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.hint-notice-container {
  border-radius: 4px;
  border: 1px solid #007bff;
  background: #e5f2ff;
  margin-left: 10px;
}

.hint-notice-content p {
  margin: 0;
  color: #007bff;
  padding: 5px;
  font-weight: bold;
  font-size: 10px;
  line-height: 1.6;
  text-align: justify;
}
// risk

.risk-notice-container {
  border-radius: 4px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  margin-left: 10px;
}

.risk-notice-content p {
  margin: 0;
  color: #ff4d4f;
  padding: 5px;
  font-weight: bold;
  font-size: 10px;
  line-height: 1.6;
  text-align: justify;
}

.compliance-alert {
  // padding: 8px 12px;
  // margin-top: 8px;
  // background: #fff2f0;
  // border: 1px solid #ffccc7;
  // border-radius: 4px;
  // color: #ff4d4f;
  display: flex;
  // align-items: center;
  // gap: 8px;
}

/* 紧凑型表单项 */
.compact-form-item {
  margin-bottom: 0; /* 减少底部间距 */
}

/* 输入框容器 */
.account-input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px; /* 元素间距 */
}

/* 紧凑型输入框 */
.compact-input {
  flex: 1;
  min-width: 120px; /* 最小宽度 */
}

/* 账号选择按钮 */
.account-select-btn {
  padding: 8px;
  margin-left: 4px;
  color: var(--el-color-primary);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .account-input-wrapper {
    flex-direction: column;
    align-items: flex-start;
  }

  .account-select-btn {
    margin-left: 0;
    margin-top: 4px;
  }
}

.contract-upload-container {
  width: 100%;
}

.legal-notice {
  margin-bottom: 8px;
  line-height: 1.5;
}

.label-text {
  // font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-regular);
}

.warning-text {
  color: #f56c6c; /* Element Plus danger 红色 */
  font-size: 12px;
  margin-left: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .legal-notice {
    display: flex;
    flex-direction: column;
  }

  .warning-text {
    margin-left: 0;
    margin-top: 2px;
  }
}
</style>
